package ink.xiaobaibai.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.tomcat.util.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;

/**
 * @description: 微信工具类
 * @author: 小白白
 * @create: 2021-06-06
 **/

public class WxUtil {

    private static String keyAlgorithm = "AES";

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 解密敏感数据,获取手机号
     */
    public static String decryptPhoneData(String iv, String encryptedData, String sessionKey) {
        byte[] ivByte = Base64.decodeBase64(iv);
        byte[] dataByte = Base64.decodeBase64(encryptedData);
        byte[] keyByte = Base64.decodeBase64(sessionKey);
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            Key sKeySpec = new SecretKeySpec(keyByte, keyAlgorithm);
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateiv(ivByte));
            byte[] data = cipher.doFinal(dataByte);
            String okData = new String(data, StandardCharsets.UTF_8);
            return JSONObject.parseObject(okData).getString("phoneNumber");
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | InvalidParameterSpecException | BadPaddingException | IllegalBlockSizeException e) {
            e.printStackTrace();
            return null;
        }
    }


    private static AlgorithmParameters generateiv(byte[] iv) throws NoSuchAlgorithmException, InvalidParameterSpecException {
        AlgorithmParameters params = AlgorithmParameters.getInstance(keyAlgorithm);
        params.init(new IvParameterSpec(iv));
        return params;
    }

}
